<template>
  <page-container title="数据任务管理">
    <div class="data-task-list">
      <!-- 操作栏 -->
      <div class="operation-bar">
        <el-button type="primary" @click="openEditDialog()">新增数据任务</el-button>
        <el-input
          v-model="searchId"
          placeholder="请输入任务ID"
          style="width: 200px; margin-left: 10px"
          @keyup.native.enter="handleSearch"
        >
          <template #append>
            <el-button icon="el-icon-search" @click="handleSearch" />
          </template>
        </el-input>
      </div>

      <!-- 数据表格 -->
      <el-table
      :data="tableData"
      style="width: 100%"
      :fit="true"
      :border="true"
      header-height="50"
      v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="100" />
        <el-table-column prop="name" label="任务名称" min-width="180" />
        <el-table-column prop="collectConfigId" label="关联数据采集配置ID" min-width="100" />
        <el-table-column prop="scheduleType" label="任务调度类型" min-width="150" />
        <el-table-column prop="status" label="状态" min-width="100" />
        <el-table-column prop="lastRunTime" label="任务上次执行时间" min-width="150" />
        <el-table-column prop="nextRunTime" label="任务下次执行时间" min-width="150" />
        <el-table-column prop="remark" label="备注" min-width="150" />
        <el-table-column label="操作" width="240" flex="right" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="mini" @click="openEditDialog(row)"
              >编辑</el-button
            >
            <el-button type="danger" size="mini" @click="handleDelete(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        class="pagination"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next"
        @current-change="handlePageChange"
      />

      <!-- 新增/编辑弹窗 -->
      <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="700px"
        @close="resetForm"
      >
        <el-form
          :model="form"
          :rules="rules"
          ref="taskForm"
          label-width="150px"
          v-loading="submitLoading"
        >
          <el-form-item label="任务名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入任务名称" maxlength="100" />
          </el-form-item>
          <el-form-item label="数据采集配置ID" prop="collectConfigId" >
            <el-select v-model="form.collectConfigId" placeholder="请选择关联数据采集配置" style="width: 100%;">
              <el-option
                v-for="item in collectConfigOptions"
                :key="item.id"
                :label="'（' + item.id + '）' + item.name "
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="任务调度类型" prop="scheduleType">
            <el-select v-model="form.scheduleType" placeholder="请选择任务调度类型" style="width: 100%;">
              <el-option label="一次性执行" value="一次性执行" />
              <el-option label="定时执行" value="定时执行" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%;">
              <el-option label="未开始" value="未开始" />
              <el-option label="执行中" value="执行中" />
              <el-option label="已完成" value="已完成" />
              <el-option label="失败" value="失败" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm">保 存</el-button>
        </div>
      </el-dialog>
    </div>
  </page-container>
</template>
<script>
import PageContainer from '@/components/PageContainer.vue'
import {
  getTaskList,
  getTaskById,
  addTask,
  updateTask,
  deleteTask
} from '@/api/task'
import { getDataCollectConfigList } from '@/api/collection'

export default {
  name: 'DataTaskList',
  components: {
    PageContainer
  },
  data () {
    return {
      tableData: [],
      loading: false,
      total: 0,
      currentPage: 1,
      pageSize: 10,
      searchId: '',
      dialogVisible: false,
      dialogTitle: '新增数据任务',
      submitLoading: false,
      form: {
        id: null,
        name: '',
        collectConfigId: '',
        scheduleType: '',
        status: '',
        lastRunTime: '',
        nextRunTime: '',
        remark: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入任务名称', trigger: 'blur' },
          { max: 100, message: '任务名称长度不能超过100个字符', trigger: 'blur' }
        ],
        collectConfigId: [
          { required: true, message: '请输入关联数据采集配置ID', trigger: 'blur' }
        ]
      },
      collectConfigOptions: []
    }
  },
  created () {
    this.loadData()
    this.loadCollectConfigOptions()
  },
  methods: {
    async loadData () {
      this.loading = true
      try {
        const params = {
          current: this.currentPage,
          size: this.pageSize,
          id: this.searchId || undefined
        }
        if (this.searchId) {
          const res = await getTaskById(this.searchId)
          console.log('searchRes', res)
          if (res.code === 200 && res.data) {
            this.tableData = [res.data]
            this.total = 1
          } else {
            this.tableData = []
            this.total = 0
            this.$message.warning(res.msg || '未找到该任务ID的数据')
          }
        } else {
          // 正常分页
          const res = await getTaskList(params)
          console.log('nomalRes', res)
          if (res.code === 200) {
            this.tableData = res.data.records || []
            this.total = res.data.total || 0
          } else {
            this.$message.error(res.msg || '获取数据任务列表失败')
            this.tableData = []
            this.total = 0
          }
        }
      } catch (error) {
        this.$message.error('获取数据任务列表失败: ' + (error.message || '未知错误'))
        this.tableData = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },
    handleSearch () {
      // 重置到第一页
      this.currentPage = 1
      console.log('searchId', this.searchId)
      // 验证输入的id是否为数字
      if (this.searchId && !/^\d+$/.test(this.searchId)) {
        this.$message.warning('请输入正确的任务ID')
        return
      }
      // 加载数据
      this.loadData()
    },
    handlePageChange (page) {
      this.currentPage = page
      this.loadData()
    },
    openEditDialog (row) {
      if (row) {
        this.dialogTitle = '编辑数据任务'
        this.getDetail(row.id)
      } else {
        this.dialogTitle = '新增数据任务'
        this.resetForm()
        this.dialogVisible = true
      }
    },
    async getDetail (id) {
      try {
        const res = await getTaskById(id)
        console.log('getDetailres', res)
        if (res.code === 200) {
          this.form = { ...res.data }
          this.dialogVisible = true
        } else {
          this.$message.error(res.msg || '获取任务详情失败')
        }
      } catch (error) {
        this.$message.error('获取任务详情失败: ' + (error.message || '未知错误'))
      }
    },
    async handleDelete (id) {
      this.$confirm('确认删除该任务？', '温馨提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async () => {
        try {
          const res = await deleteTask(id)
          if (res.code === 200) {
            this.$message.success('删除成功！')
            this.loadData()
          } else {
            this.$message.error('删除失败：' + (res.msg || '未知错误'))
          }
        } catch (error) {
          this.$message.error('删除失败：' + (error.message || '未知错误'))
        }
      })
    },
    resetForm () {
      this.form = {
        id: null,
        name: '',
        collectConfigId: '',
        scheduleType: '',
        status: '',
        lastRunTime: '',
        nextRunTime: '',
        remark: ''
      }
    },
    submitForm () {
      this.$refs.taskForm.validate(async valid => {
        if (!valid) return
        this.submitLoading = true
        try {
          let res
          if (this.form.id) {
            res = await updateTask(this.form)
          } else {
            res = await addTask(this.form)
          }
          if (res.code === 200) {
            this.$message.success(this.form.id ? '修改成功' : '添加成功')
            this.dialogVisible = false
            this.loadData()
          } else {
            this.$message.error(res.msg || (this.form.id ? '修改失败' : '添加失败'))
          }
        } catch (error) {
          this.$message.error((this.form.id ? '修改失败' : '添加失败') + ': ' + (error.message || '未知错误'))
        } finally {
          this.submitLoading = false
        }
      })
    },
    async loadCollectConfigOptions () {
      try {
        const res = await getDataCollectConfigList({ current: 1, size: 1000 })
        if (res.code === 200) {
          this.collectConfigOptions = res.data.records || []
        }
      } catch (e) {
        this.collectConfigOptions = []
      }
    }
  }
}
</script>
<style scoped>
.operation-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: end;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
.el-table th{
  vertical-align: middle;
  line-height: 60px;
}
.data-task-list {
  width: 100%;
  padding: 0;
  margin: 0;
}
.data-task-list >>> .el-table th {
  height: 100px;
  line-height: 100px;
  vertical-align: middle;
  padding: 0;
}
</style>
